package com.example.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.common.to.SeckillOrderTo;
import com.example.common.utils.R;
import com.example.common.vo.MemberResponseVo;
import com.example.gulimall.seckill.constant.SeckillConstant;
import com.example.gulimall.seckill.feign.CouponFeignService;
import com.example.gulimall.seckill.feign.ProductFeignService;
import com.example.gulimall.seckill.interceptor.LoginInterceptor;
import com.example.gulimall.seckill.service.SeckillService;
import com.example.gulimall.seckill.to.SeckillSkuRedisTo;
import com.example.gulimall.seckill.vo.SeckillSessionWithSkusVo;
import com.example.gulimall.seckill.vo.SkuInfoVo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public void uploadSeckillSkuLatest3Days() {
        R session = couponFeignService.getLates3DaySession();
        if((int)session.get("code")==0){
            List<SeckillSessionWithSkusVo> sessionData = session.getData(new TypeReference<List<SeckillSessionWithSkusVo>>() {
            });
            //在redis中分别保存秒杀场次信息和场次对应的秒杀商品信息
            saveSecKillSession(sessionData);
            saveSecKillSku(sessionData);
        }
    }

    @Override
    public SeckillSkuRedisTo getSeckillSkuInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SECKILL_CHARE_PREFIX);
        Set<String> keys = ops.keys();
        for (String key : keys) {
            String s="\\d-" + skuId;
            if(Pattern.matches(s,key)){
                String target = ops.get(key);
                SeckillSkuRedisTo redisTo = JSON.parseObject(target, SeckillSkuRedisTo.class);
                if(redisTo!=null){
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    long currentTimeMillis = System.currentTimeMillis();
                    if(currentTimeMillis>=startTime&&currentTimeMillis<=endTime){
                        return redisTo;
                    }
                    redisTo.setRandomCode("");
                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) throws InterruptedException {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SECKILL_CHARE_PREFIX);
        MemberResponseVo memberResponseVo = LoginInterceptor.threadLocal.get();
        String json = ops.get(killId);
        String orderSn=null;
        if(StringUtils.isNotEmpty(json)){
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //1. 验证时效
            long current = System.currentTimeMillis();
            //2. 验证商品和商品随机码是否对应
            if (current >= redisTo.getStartTime() && current <= redisTo.getEndTime() && key.equals(redisTo.getRandomCode())){
                //3. 验证当前用户是否购买过
                long ttl=redisTo.getEndTime()-System.currentTimeMillis();
                //3.1 通过在redis中使用 用户id-skuId 来占位看是否买过
                Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(memberResponseVo.getId()
                        + "-" + redisTo.getSkuId(), num.toString(), ttl, TimeUnit.MILLISECONDS);
                //3.2 占位成功，说明该用户未秒杀过该商品，则继续
                if(ifAbsent && num<=redisTo.getSeckillLimit()){
                    //4.1 尝试获取库存信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + key);
                    boolean tryAcquire = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                    //4.2 获取库存成功
                    if(tryAcquire){
                        //5. 发送消息创建订单
                        //5.1 创建订单号
                        orderSn = IdWorker.getTimeId();
                        //5.2 创建秒杀订单to
                        SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                        seckillOrderTo.setMemberId(memberResponseVo.getId());
                        seckillOrderTo.setNum(num);
                        seckillOrderTo.setOrderSn(orderSn);
                        seckillOrderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                        seckillOrderTo.setSeckillPrice(redisTo.getSeckillPrice());
                        seckillOrderTo.setSkuId(redisTo.getSkuId());
                        //5.3 发送创建订单的消息
                        rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
                    }
                }
            }
        }
        return orderSn;
    }

    private void saveSecKillSku(List<SeckillSessionWithSkusVo> sessionData) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SeckillConstant.SECKILL_CHARE_PREFIX);
        sessionData.forEach(session -> {
            session.getRelationSkus().forEach(sku -> {
                String key = sku.getPromotionSessionId() + "-" + sku.getSkuId();
                if(!hashOps.hasKey(key)){
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1. 保存SeckillSkuVo信息
                    BeanUtils.copyProperties(sku,redisTo);
                    //2. 保存开始结束时间
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    R info = productFeignService.info(sku.getSkuId());
                    if((int)info.get("code")==0){
                        SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(skuInfo);
                    }
                    //4. 生成商品随机码，防止恶意攻击
                    String token = UUID.randomUUID().toString().replace("-", "");
                    redisTo.setRandomCode(token);
                    //5. 序列化为json并保存
                    String s = JSON.toJSONString(redisTo);
                    hashOps.put(key,s);
                    //6. 使用库存作为Redisson信号量限制库存
                    RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(sku.getSeckillCount());
                }
            });
        });
    }

    private void saveSecKillSession(List<SeckillSessionWithSkusVo> sessionData) {
        sessionData.forEach(item->{
            String key= SeckillConstant.SESSION_CACHE_PREFIX+item.getStartTime().getTime()+"_"+
                    item.getEndTime().getTime();
            if(!redisTemplate.hasKey(key)){
                List<String> skuInformation = item.getRelationSkus().stream().map(sku -> {
                    return sku.getPromotionSessionId() + "-" + sku.getSkuId();
                }).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,skuInformation);
            }
        });
    }
}
